<?php

namespace app\web\controller;
use app\web\model\LineMemberModel;
use app\web\model\LineMemberLevelModel;
use app\web\model\LineAttributesModel;
use app\web\model\LineRechlogModel;
use app\web\model\LineMemchargelogModel;
use app\admin\model\Member as MemberModel;
use app\common\controller\StoreBaseController;
use app\common\model\Csv;

use think\Db;
//use vendor\PHPExcel\PHPExcel;
/**
 * 线下会员列表
 */
class LineMemberController extends StoreBaseController
{
 	protected $model;
	protected $attr_model;
 	protected $csv;
	
    protected function _initialize() {
        parent::_initialize();
        $this->model = new LineMemberModel();
		//自定义属性
		$this->attr_model = new LineAttributesModel();
		//会员等级
		$this->modelevel = new LineMemberLevelModel();
        $this->csv = new Csv();
        $member_level = $this->modelevel->where('agent_id',session('storeInfo')['id'])->select();
		$this->assign('member_level',$member_level);
        
    }
	
    /**
     * 线下会员列表
     * @author [longx] 
     */
    public function index( $page = 1){
    	if(request()->isPost()){
		 	$param = input('post.');
			//会员名称
			if($param['membername']){
				$where['b.membername'] = ['like', '%'.$param['membername'].'%'];
			}
			//手机号码
			if($param['mobile']){
				$where['b.mobile'] = ['like', '%'.$param['mobile'].'%'];
			}
			//会员卡号
			if($param['member_no']){
				$where['b.member_no'] = ['like', '%'.$param['member_no'].'%'];
			}	
			//有效期
			if($param['start_time']&&$param['end_time']){
				$where['b.validity_date'] = ['between time', [$param['start_time'],$param['end_time']]];
			}		 				
	 	}
    	$where['store_id']= session('storeInfo')['id'];
        $list = Db::name("line_member")->alias('b')
        ->join('long_line_memberlevel m','m.id = b.member_gradeid','LEFT')
        ->field('b.*,m.levelname')->where($where)->order('b.reg_date desc')->paginate(10);
        return $this->fetch('index', ['list' => $list]);
    }


    /**
     * 
     *添加
     * @author [longx] 
     */
    public function add()
    {
        if(request()->isAjax()){
        	$param=input('post.');
			$param['reg_date'] = now_time();
			$param['store_id'] = session('storeInfo')['id'];
			$param['store_name'] = session('storeInfo')['store_name'];
			$param['is_lock'] = input('is_lock') ? true : false;
			if ($this->model->allowField(true)->save($param) !== false) {
			    	$member_model = new MemberModel();
					$member=$member_model->where('mobile',input('mobile'))->find();
					if(!$member){						
						$member_model->login_time = now_time();
						$member_model->mobile = input('mobile');
						$member_model->pid = session('storeInfo')['u_id'];
						$member_model->password=md5_salt(substr(input('mobile'), -6));
						$member_model->pay_password=md5_salt(substr(input('mobile'), -6));
						$member_model->login_ip = $this->request->ip();
						$result = $member_model->allowField(true)->save();
					}
                    $this->success('添加成功', url('line_member/index'));
            } else {
                $this->error('添加失败');
            }
        }
    	$store_id = session('storeInfo')['id'];
		$this->assign('attr',$this->attr_model->where('store_id',$store_id)->find());
        return $this->fetch();
    }

	/**
	 * 根据工号查找员工
	 */
	public function get_emp(){
		$emp=db("line_employee")->alias('a')->join('line_zhiwei b ','b.id= a.z_id')->field("a.*,b.name as zname")->where("no",input("no"))->find();
		exit(json_encode($emp));
	}
    
	
	//批量添加
	public function padd($p='1',$p1='1'){
		if($p == '1' || $p1=='1'){
			return $this->fetch('padd',['list'=>'1','list1'=>'1']);  
		} else{
			$p= explode(',', $p);
			$p1= explode(',', $p1);
			return $this->fetch('padd',['list'=>$p,'list1'=>$p1]);   
		}
	}	
	
	
	public function padd_ok(){
		$fileName = 'public/upload/'.$_FILES['myfile']['name'];
		$arr_sql=$this->csv->dr($fileName);
		$f=array();
		for($i=1;$i<count($arr_sql);$i++){
			$agent_id=session('storeInfo')['id'];
			$row=$arr_sql[$i];
			$row=explode(',', $row);
			$where['mobile'] =$row['2'];
			$where['store_id'] =$agent_id;
			$where['member_no']=$row['0'];
			if($this->model->where($where)->find()){
				$f[]=$row['2'];
				$b[]=$row['0'];
			}else{
				$rows=Db::name('mall_agent')->where('id',$agent_id)->find();
				$data[$i-1]['member_no']=$row['0'];
				$data[$i-1]['membername']=$row['1'];
				$data[$i-1]['mobile']=$row['2'];
				$data[$i-1]['address']=$row['3'];
				$data[$i-1]['member_gradeid']=$row['4'];
				$data[$i-1]['newblanceflg']=$row['5'];
				$data[$i-1]['newbonusflg']=$row['6'];
				$data[$i-1]['store_name']=$rows['store_name'];
				$data[$i-1]['reg_date']=date("Y-m-d H:i:s");
				$data[$i-1]['store_id']=$agent_id;
			}
		}
		$p=implode(',', $f);
		$p1=implode(',', $b);

		$data=isset($data)?$data:"";
		if($data){
			if(Db::name('line_member')->insertAll($data)){				
		 		$this->success('批量添加成功', url('padd',['p'=>$p,'p1'=>$p1]));
		 	}else{
        		$this->success('批量添加失败' , url('padd',['p'=>$p,'p1'=>$p1]));
			}
		}else{
			$this->success('批量添加失败' , url('padd',['p'=>$p,'p1'=>$p1]));
		}					
	}

	//导出csv文件
     public function dc($data){
     	if($data == '1'){
     	$agent_id=session('storeInfo')['id'];
     	$result = $this->model->where('store_id',$agent_id)->select();
     	}
		$str="卡号,姓名,电话,地址,等级,余额,积分,注册时间,";//设置导出第一行
        if($data == '1'){
        	$list="member_no,membername,mobile,address,member_gradeid,newblanceflg,newbonusflg,reg_date";//设置导出字段
        	$filename ='下线会员表.csv';//设置文件名
        	$this->csv->dc($str,$list,$result,$filename);
        }else{
        	$str="卡号,姓名,电话,地址,等级,余额,积分,";
        	$list="";
        	$result="";
        	$filename ='csv导入样板.csv';
        	$this->csv->dc($str,$list,$result,$filename);
        }


     }


    /**
     * [edit 编辑]
     * @return [type] [description]
     * @author [longx]
     */
    public function edit($id)
    {
        if(request()->isAjax()){
            $param = input('post.');         
			$param['is_lock'] = input('is_lock') ? true : false;
         	if ($this->model->allowField(true)->save($param,$id) !== false) {
                $this->success('修改成功', url('line_member/index'));
            } else {
                $this->error('修改失败');
            }
        }
        $id = input('param.id');
        $this->assign('ad',$this->model->where('id',$id)->where('store_id',session('storeInfo')['id'])->find());
		$this->assign('attr',$this->attr_model->where('store_id',session('storeInfo')['id'])->find());
        return $this->fetch();
    }


    /**
     * [del删除]
     * @author [longx] 
     */
    public function delete()
    {
        $id = input('param.id');
        if ($this->model->destroy($id)) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
    /**
	 * 批量删除
	 */
	public function dels() {
			$params=input("");
			$ids = implode(",", $params['chk']);
			$res=$this->model->where("id","in",$ids)->delete();
			if($res){
				  return json(['code'=>200,'msg'=>"删除成功 "]);
			}else{
				  return json(['code'=>406,'msg'=>"删除失败 "]);
			}
			
	}
    /**
     * [查看会员详情]
     * 消费记录
     * @author [] 
     */
    public function memberInfo($page = 1)
    {   
    	//将会员ID存session
    	$id=input('param.id');
    	session('member_id', $id);   	
    	$where['a.agent_id'] = session('storeInfo')['id'];
		$where['a.line_member_id'] =$id;
		if(request()->isPost()){
		 	$param = input('post.');
			if($param['member_no']){				
				$where['b.member_no'] = ['like', '%'.$param['member_no'].'%'];
			}
		}
		$list = db("line_order")->alias('a')->join('line_member b','a.line_member_id=b.id','LEFT')->where($where)->paginate(10);		
		return $this->fetch('memberInfo', ['list' => $list,'id'=>session('member_id')]);        
    }
    
    /**
     * 充值记录
     * @author [] 
     */
    public function chongzhiInfo($page = 1)
    {
    	$field='a.*,b.id as b_id,b.member_no';
    	$id=input('param.id');
    	$where['a.store_id'] = session('storeInfo')['id'];
		$where['a.member_id'] =$id;
		if(request()->isPost()){
		 	$param = input('post.');
			if($param['member_no']){
				$where['b.member_no'] = ['like', '%'.$param['member_no'].'%'];
			}
		}
		$list = db('LineRechlog')->alias('a')->field($field)->join('line_member b','a.member_id=b.id','LEFT')->where($where)->paginate(10);
		//echo  db("LineRechlog")->getLastSql();
		return $this->fetch('chongzhiInfo', ['list' => $list,'id'=>session('member_id')]);  	
    }
    /**
     * 充次记录
     * @author [] 
     */
    public function chongciInfo($page = 1)
    {   
    	$field='a.*,b.id as b_id,b.member_no';
    	$id=input('param.id');
    	$where['a.store_id'] = session('storeInfo')['id'];
		$where['a.line_member_id'] =$id;
		if(request()->isPost()){
		 	$param = input('post.');
			if($param['member_no']){
				$where['b.member_no'] = ['like', '%'.$param['member_no'].'%'];
			}
		}
		$list = db('LineMemchargelog')->alias('a')->field($field)->join('line_member b','a.line_member_id=b.id','LEFT')->where($where)->paginate(10);
		return $this->fetch('chongciInfo', ['list' => $list,'id'=>session('member_id')]);  
    }
    /**
     * 积分记录
     * @author [] 
     */
    public function jifenInfo($page = 1)
    {
    	$field='a.*,b.id as b_id,b.member_no';
    	$id=input('param.id');
    	$where['a.store_id'] = session('storeInfo')['id'];
		$where['a.line_member_id'] =$id;
		if(request()->isPost()){
		 	$param = input('post.');
			if($param['member_no']){
				$where['b.member_no'] = ['like', '%'.$param['member_no'].'%'];
			}
		}
		$list = db('LineExchangelog')->alias('a')->field($field)->join('line_member b','a.line_member_id=b.id','LEFT')->where($where)->paginate(10);
    	return $this->fetch('jifenInfo',['list' => $list,'id'=>session('member_id')]);
    }
    
}